package com.mazaiting.gateway.config;

import com.mazaiting.gateway.domain.CorsBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;

/***
 * 网关跨域配置
 *
 * @author mazaiting
 * @since 2021/4/9
 */
@Configuration
public class CorsConfig {

    @Resource
    private CorsBean corsBean;

    /**
     * Web 跨域配置
     *
     * @return 跨域过滤器
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 是否允许携带 cookie
        config.setAllowCredentials(true);
        // 可接受的域, 是一个具体域名或者*(代表任意域名)
        // config.addAllowedOrigin("*"); // 旧版本使用这个
//        config.addAllowedOriginPattern("*");
        config.setAllowedOrigins(corsBean.getUrls());
        // 允许携带的头
        config.setAllowedHeaders(Collections.singletonList("*"));
        // 允许访问的方式
        config.setAllowedMethods(Arrays.asList(
                HttpMethod.GET.name(),
                HttpMethod.POST.name(),
                HttpMethod.OPTIONS.name(),
                HttpMethod.PUT.name(),
                HttpMethod.DELETE.name(),
                HttpMethod.PATCH.name()
        ));
//        config.addAllowedMethod("*");

        // 设置所有请求执行该配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}


















